package unitTests;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import junit.framework.Assert;

/**
 * Provides access to private members in classes.
 * Taken and adapted from
 * http://onjava.com/pub/a/onjava/2003/11/12/reflection.html?page=1
 * by Ross Burton
 * 11/12/2003 
 */
public class PrivateAccessor {

	public static Object getPrivateMethod(Object o, String methodName,
			Object parameters[]) {
		/* Check we have valid arguments */
		Assert.assertNotNull(o);
		Assert.assertNotNull(methodName);
		/* Go and find the private method... */
		final Method[] methods = o.getClass().getDeclaredMethods();
		for (int i = 0; i < methods.length; ++i) {
			if (methodName.equals(methods[i].getName())) {
				final Object params[] = parameters;
				methods[i].setAccessible(true);
				try {
					return methods[i].invoke(o, params);
				} catch (IllegalAccessException e) {
					Assert.fail("IllegalAccessException accessing "
							+ methodName);
				} catch (IllegalArgumentException e) {
					Assert.fail("IllegalArgumentException accessing "
							+ methodName + "with parameters: " + parameters);
				} catch (InvocationTargetException e) {
					Assert.fail("InvocationTargetException accessing "
							+ methodName);
				}
			}
		}

		Assert.fail("Method '" + methodName + "' not found");
		return null;
	}
}